/********************* 公共函数(依赖app上的插件(如:axios、router),模板渲染会报错) *******************************************/
import ViewUI from 'view-design';
export default ({app}, inject) => {
  // Inject $hello(msg) in Vue, context and store.
  inject('cache', (key,val,ttl) => cache(key,val,ttl));
  inject('cacheRemove', key => cacheRemove(key));
  inject('formatDatetime', (date,partten, split) => formatDatetime(date,partten, split));
  inject('requestGet', (url,params,header,message,success,fail,error) => request(app,url,params,"get",header,message,success,fail,error));
  inject('requestPost', (url,params,header,message,success,fail,error) => request(app,url,params,"post",header,message,success,fail,error));
  inject('request', (url,params,method,header,message,success,fail,error) => request(app,url,params,method,header,message,success,fail,error));
  inject('upload', (url,params,timeout,method) => upload(app,url,params,timeout,method));
  inject('download', (url,fileName,method,fileType) => download(app,url,fileName,method,fileType));
}

/**
 * axios请求
 * @param app
 * @param url
 * @param params
 * @param method
 * @param header
 * @param message
 * @param success
 * @param fail
 * @param error
 */
function request(app,url,params={},method = "post",header={},message=false,success,fail,error){
  //ViewUI.Spin.show();
  return app.$axios({
    url: url,
    method: method,
    headers:{...header},
    data: {...params},
  }).then(res=>{
    //ViewUI.Spin.hide();
    if (res.code == 0){
      message && ViewUI.Message.success("操作成功");
      success && success(res.data);
    }else if (res.code == 2){
      message && ViewUI.Message.warning("未登录");
      localStorage.removeItem("userInfo");
      app.router.push('/');
    }else {
      message && ViewUI.Message.error(res.msg || "操作失败");
      fail && fail(res);
    }
    return res;
  }).catch(err => {
    //ViewUI.Spin.hide();
    console.log('%c ! Send Request Error','background:#000;color:#bada55',err);
    !error ? ViewUI.Message.error('服务异常') : (typeof(error) == 'string' ? ViewUI.Message.error(error) : error(err));
    return err;
  });
}

/**
 * 上传文件
 * @param app
 * @param url
 * @param params
 * @param timeout
 * @param method
 */
function upload(app,url,params,timeout,method="post"){
  return app.$axios({
    url: url,
    method: method,
    data: params,
    timeout: timeout || 60000000,
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  }).catch(error => {
    console.log('%c ! Upload Error','background:#000;color:#bada55',error);
    ViewUI.Message.error('上传异常');
    return error;
  }).then(response => {
    if (response && (response.code == 0)){
      ViewUI.Message.success('上传成功');
      return response;
    }
  })
}

/**
 * 下载文件
 * @param app
 * @param url
 * @param fileName
 * @param method
 * @param fileType
 */
function download(app,url,fileName,method="get",fileType="application/vnd.ms-excel"){
  return app.$axios({
    url: url,
    method: method,
    responseType:'blob'
  }).then(response => {
    //const blob = new Blob([response],{type: response.headers["Content-Type"]});
    var blob = new Blob([response]);
    if (response && response.headers && response.headers["Content-Type"] && !fileType){
      blob = new Blob([response],{type: response.headers["Content-Type"]});
    }else if (fileType){
      // 类型 fileType = "application/vnd.ms-excel" / "application/pdf"
      blob = new Blob([response],{type: fileType});
    }
    if (!fileName){
      fileName = formatDatetime(new Date());
    }
    var link = document.createElement("a");
    link.href = window.URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    //释放内存
    window.URL.revokeObjectURL(link.href);
    return response;
  }).catch(error => {
    console.log('%c ! Download Error','background:#000;color:#bada55',error);
    ViewUI.Message.error('下载异常');
    return error;
  })
}

/**
 * 时间格式化
 * @param partten yyy
 * @param split
 * @returns {string|number}
 */
function formatDatetime(date,partten, split){
  if (date == '' || date == null || date == undefined)return;
  partten = partten || 'yyyy-MM-dd';
  split = split || '';
  var date = new Date(date),
    year = date.getFullYear(),
    month = date.getMonth() + 1,
    day = date.getDate(),
    hh = date.getHours(),
    mm = date.getMinutes(),
    ss = date.getSeconds();
  month = month > 9 ? month : ('0' + month);
  day = day > 9 ? day : ('0' + day);
  hh = hh > 9 ? hh : ('0' + hh);
  mm = mm > 9 ? mm : ('0' + mm);
  ss = ss > 9 ? ss : ('0' + ss);
  if (partten == 'yyyy') {
    return year;
  } else if (partten == ('yyyy' + split + 'MM')) {
    return year + split + month;
  } else if (partten == 'yyyy' + split + 'MM' + split + 'dd') {
    return year + split + month + split + day;
  } else if (partten == 'yyyy' + split + 'MM' + split + 'dd HH') {
    return year + split + month + split + day + ' ' + hh;
  } else if (partten == 'yyyy-MM-dd HH:mm') {
    return year + split + month + split + day + ' ' + hh + split + mm;
  } else if (partten == 'yyyy-MM-dd HH:mm:ss') {
    return year + split + month + split + day + ' ' + hh + split + mm + split + ss;
  }else {
    return year + split + month + split + day + hh + split + mm + split + ss;
  }
}

/**
 * 设置与获取缓存
 * @param key
 * @param val
 * @param ttl
 * @returns {string|any|void}
 */
function cache(key, val, ttl){
  if (val){
    const it = {
      value:val,
      expired:0
    };
    if (ttl){
      var time = new Date();
      it.expired = time.getTime() + ttl;
    }
    return localStorage.setItem(key, JSON.stringify(it));
  }
  var time = new Date();
  var item = localStorage.getItem(key);
  if (item){
    item = JSON.parse(item);
    if (item.expired !==0 && time.getTime() > item.expired){
      localStorage.removeItem(key);
      return null;
    }
    return item.value;
  }
  return item;
}

/**
 * 移除缓存
 */
function cacheRemove(key){
  return localStorage.removeItem(key);
}
